package client_updater

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor
import scala.actors.remote.RemoteActor._
import db.Client
import java.io.FileInputStream

/**
 * Listens to clients that check for new updates, and sends them an update if exists.<br>
 * Works as a remote actor that listens to messages on a given port.<br>
 * @param - port : Int, a port to listen on
 */
class UpdatesActor(port: Int) extends Actor {

  /**
   * The acting method of the actor.<br>
   * Receives messages about a client checking for new updates and gets an update for him
   * from the ClientsUpdater, and sends it back to the client.
   */
  def act() {
    alive(port)
    register('Updater, self)
    loop {
      react {
        case (uid: Long, cid: Long) => {
          println("checking for updates !!")
          var client = new Client
          client.setUserID(uid)
          client.setClientID(cid)
          var update = ClientsUpdater.getUpdate(cid)
          if(update != null) println(update.mes)
          if (update == null){
            println ("no updates")
            sender ! "Done"
          }
          else if (update.mes == "newFile" || update.mes == "changedFile") {
             val file=new java.io.File("storage\\"+update.asInstanceOf[FileUpdate].id)
             val fis=new FileInputStream(file)
             var bytes=new Array[Byte](file.length.asInstanceOf[Int])
             fis.read(bytes)
             fis.close
             println("sending file")
             sender ! (update.mes, update.nm, update.prnt, bytes)
          } else if (update.mes == "newFolder") {
            sender ! (update.mes, update.nm, update.prnt, update.asInstanceOf[FolderUpdate].fid)
          } else if (update.mes == "deletedFile" || update.mes == "deletedFolder" || update.mes == "upload") {
            sender ! (update.mes, update.nm, update.prnt)
          } else
            sender ! update.mes
        }

      }
    }
  }
}